package com.kzj.laimeimei.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;

import com.ab.util.AbSharedUtil;
import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.kzj.laimeimei.R;
import com.kzj.laimeimei.beans.CityBean;
import com.kzj.laimeimei.beans.CropImageBean;
import com.kzj.laimeimei.beans.UserBean;
import com.kzj.laimeimei.beans.UserInfoCardBean;
import com.kzj.laimeimei.global.App;
import com.kzj.laimeimei.global.Constant;
import com.kzj.laimeimei.recyclerCard.basic.MaterialListAdapter;
import com.kzj.laimeimei.recyclerCard.basic.MaterialListView;
import com.kzj.laimeimei.recyclerCard.basic.OnButtonPressListener;
import com.kzj.laimeimei.recyclerCard.card.Card;
import com.kzj.laimeimei.recyclerCard.card.other.AlphaCard;
import com.kzj.laimeimei.recyclerCard.card.other.CityCard;
import com.kzj.laimeimei.recyclerCard.card.other.UserInfoCard;
import com.kzj.laimeimei.request.BaseResponse;
import com.kzj.laimeimei.request.ICallBackForRequestServer;
import com.kzj.laimeimei.request.RequestServerManager;
import com.kzj.laimeimei.util.BitmapUtils;
import com.kzj.laimeimei.widget.dialog.CameraDialog;
import com.kzj.laimeimei.widget.dialog.CameraDialogAction;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


public class UserInfoActivity extends GBaseActivity {
    private MaterialListView material_listview;
    private TextView textView_cancel;
    private CameraDialog cameraDialog;
    public Uri photoUri;
    private static final int REQUEST_GALLERY = 21;
    public final int CAMERA = 10001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_user_info);
        findViewByIds();
        initDatas();
        fillArrayInListView();
    }

    @Override
    protected void findViewByIds() {
        material_listview = (MaterialListView) findViewById(R.id.material_listview);
        textView_cancel = (TextView) findViewById(R.id.textView_cancel);
        textView_cancel.setOnClickListener(this);
    }

    @Override
    protected void initDatas() {
        setTopTitle("我的账号");
        setLeftImg(View.VISIBLE, R.drawable.back);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void fillArrayInListView() {
        for (int i = 0; i < 3; i++) {
            UserInfoCard userInfoCard = new UserInfoCard(this);
            UserInfoCardBean userInfoCardBean = new UserInfoCardBean();
            switch (i) {
                case 0:
                    userInfoCardBean.setPosition(0);
                    userInfoCardBean.setIsNeedImage(true);
                    userInfoCardBean.setIsNeedLine(true);
                    userInfoCardBean.setIsNeedArrow(true);
                    userInfoCardBean.setItemName("头像");
                    break;
                case 1:
                    userInfoCardBean.setPosition(1);
                    userInfoCardBean.setIsNeedImage(false);
                    userInfoCardBean.setIsNeedLine(true);
                    userInfoCardBean.setIsNeedArrow(true);
                    userInfoCardBean.setItemName("昵称");
                    break;
                case 2:
                    userInfoCardBean.setPosition(2);
                    userInfoCardBean.setIsNeedImage(false);
                    userInfoCardBean.setIsNeedLine(false);
                    userInfoCardBean.setIsNeedArrow(false);
                    userInfoCardBean.setItemName("手机");
                    break;
            }
            userInfoCard.setUserInfoCardBean(userInfoCardBean);
            userInfoCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
                @Override
                public void onButtonPressedListener(View view, Card card) {
                    Intent intent;
                    switch (((UserInfoCard) card).getUserInfoCardBean().getPosition()) {
                        case 0:
                            showCameraDialog();
                            break;
                        case 1:
                            intent = new Intent(UserInfoActivity.this, ChangeNameActivity.class);
                            startActivity(intent);
                            break;
                        case 2:
                            break;
                    }
                }
            });
            material_listview.add(userInfoCard);
        }
        AlphaCard alphaCard = new AlphaCard(this);
        alphaCard.setItemHeight(AbViewUtil.scaleValue(this, 10));
        alphaCard.setIsNeedTopLine(true);
        material_listview.add(alphaCard);
    }

    public void showCameraDialog() {
        if (cameraDialog == null) {

            cameraDialog = CameraDialog.create(getActivity(),
                    new CameraDialogAction() {

                        @Override
                        public void clickCamera() {

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                                    "yyyy_MM_dd_HH_mm_ss");
                            String filename = timeStampFormat.format(new Date());
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Images.Media.TITLE, filename);

                            photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

                            startActivityForResult(intent, CAMERA);
                        }

                        @Override
                        public void clickAblum() {
                            //先跳到发布页面
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, REQUEST_GALLERY);

                        }
                    });

        }
        cameraDialog.show();
    }

    public void onEventMainThread(UserBean userBean) {
        material_listview.getAdapter().notifyDataSetChanged();
    }

    protected void fillArrayInListView(List<CityBean> cityBeanList) {
        for (int i = 0; i < cityBeanList.size(); i++) {
            CityCard cityCard = new CityCard(this);
            cityCard.setCityBean(cityBeanList.get(i));
            material_listview.add(cityCard);
        }

    }

    private void TaskGetUserInfo() {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_config_city, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_config_city), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        List<CityBean> cityBeanList = JSON.parseArray(JSON.toJSONString(result.getRetval()), CityBean.class);
                        fillArrayInListView(cityBeanList);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.textView_cancel:
                AbSharedUtil.putString(this, Constant.SystemContext.UserBean, null);
                App.getInstance().setUserBean(null);
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent resultIntent) {
        super.onActivityResult(requestCode, responseCode, resultIntent);
        switch (requestCode) {
            case REQUEST_GALLERY:
                String absPath = BitmapUtils.getFilePathFromUri(this, resultIntent.getData());
                Intent intent = new Intent(UserInfoActivity.this, CropImageActivity.class);
                intent.putExtra(CropImageActivity.ImageUrlTag, absPath);
                intent.putExtra(CropImageActivity.ActivityTag, this.getLocalClassName());
                startActivity(intent);

                break;
            case CAMERA:
                if (resultIntent != null && resultIntent.getData() != null) {
                    photoUri = resultIntent.getData();
                }
                String imagePath = BitmapUtils.getFilePathFromUri(this, photoUri);
                Intent intent2 = new Intent(UserInfoActivity.this, CropImageActivity.class);
                intent2.putExtra(CropImageActivity.ImageUrlTag, imagePath);
                intent2.putExtra(CropImageActivity.ActivityTag, this.getLocalClassName());
                startActivity(intent2);

                //  App.displayImageHttpOrFile(getImagePathFromCamera(resultIntent,UserInfoActivity.this,photoUri),imageView_test, ImageUtil.OptionsNormal());

                break;
        }
    }

    public String getImagePathFromCamera(Intent resultIntent, Activity activity, Uri uri) {

        String[] proj = {MediaStore.MediaColumns.DATA};
        Cursor cursor = null;
        if (activity != null) {
//				@SuppressWarnings("deprecation")
            cursor = activity.managedQuery(uri, proj, null, null, null);
        }
//			Cursor cursor = actvity.managedQuery(uri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        cursor.moveToFirst();
        String imagePath = cursor.getString(column_index);
        return imagePath;
    }

    //更新头像
    public void onEventMainThread(CropImageBean cropImageBean) {
        //图片回调涉及多个类，防止无关类加载
        if (cropImageBean.getActivityString().equals(this.getLocalClassName())) {
            MaterialListAdapter materialListAdapter = (MaterialListAdapter) (material_listview.getAdapter());
            UserInfoCard userInfoCard = (UserInfoCard) materialListAdapter.getCard(0);
            userInfoCard.getUserInfoCardBean().setImageUrl(cropImageBean.getImageUrl());
            App.getInstance().getUserBean().getUser_info().setPortrait(cropImageBean.getImageUrl());
            App.getInstance().setUserBean(App.getInstance().getUserBean());
            materialListAdapter.notifyDataSetChanged();
            TaskUpdateHeadImage(cropImageBean.getImageUrl());

        }
    }

    private void TaskUpdateHeadImage(final String fileUrl) {
        File file = new File(fileUrl);
        HashMap<String, File> hashMapFile = new HashMap<>();
        hashMapFile.put("portrait", file);

      /*  byte[] myByteArray = new byte[1024];
        RequestParams params = new RequestParams();
        try {
            params.put("portrait", file,"application/octet-stream");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        //    params.put("portrait", new ByteArrayInputStream(myByteArray), fileUrl);
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_UpdateHeadImage, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_UpdateHeadImage, hashMapFile, null, null), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        if (result.getDone().equals(Constant.SystemContext.SuccessState)) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(2000);
                                        App.imageLoader.clearDiskCache();
                                        App.imageLoader.clearMemoryCache();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }).run();
                            App.getInstance().showToast("修改成功");
                            // App.getInstance().getUserBean().getUser_info().setPortrait(fileUrl);
                            // App.getInstance().setUserBean( App.getInstance().getUserBean());
                        }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
        MobclickAgent.onResume(this);          //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }
}
